package sau.diyizu.media.menu;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import sau.diyizu.media.ItemListener;
import sau.diyizu.media.R;

import java.util.List;

/**
 @author JYD
 @version 1.0
 @since 2020/12/16 20:16 */
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.VH> {

    private List<MenuItem> items;
    private LayoutInflater inflater;
    private ItemListener listener = ItemListener.DEFAULT_NULL_INSTANCE;

    public void setDataAndNotify(List<MenuItem> items) {
        this.items = items;
        notifyDataSetChanged();
    }

    public void setItemListener(ItemListener listener) {
        this.listener = listener;
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        inflater = LayoutInflater.from(recyclerView.getContext());
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        VH vh = new VH(inflater.inflate(R.layout.item_menu, parent, false));
        vh.itemView.setOnClickListener(v -> listener.onTrigger(vh));
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        MenuItem item = items.get(position);
        holder.icon_v.setBackgroundResource(item.iconRes);
        holder.name_tv.setText(item.name);
    }

    @Override
    public int getItemCount() {
        return items != null ? items.size() : 0;
    }

    static class VH extends RecyclerView.ViewHolder {
        View icon_v;
        TextView name_tv;

        public VH(@NonNull View itemView) {
            super(itemView);
            icon_v = itemView.findViewById(R.id.icon_v);
            name_tv = itemView.findViewById(R.id.name_tv);
        }
    }
}
